<template>
  <div class="height-100-per width-100-per bg-color-white padding-10-px">
    <div class="width-100-per layout-side margin-bottom-10-px">
      <div>
        <a-button-group v-if="userType==='2'" style="padding: 10px 10px 0">
          <a-button style="width: 110px" icon="plus" @click="addMaterial">材料新增</a-button>
          <a-button v-if="!updateSomeMaterials" style="width: 110px" icon="edit" @click="deleteSomeMaterial">批量删除</a-button>
          <a-button v-if="updateSomeMaterials" style="width: 77px" icon="close" @click="deleteSomeMaterialCancle">取消</a-button>
          <a-button v-if="updateSomeMaterials" style="width: 77px" icon="delete" @click="deleteSomeMaterialOK">确定</a-button>
        </a-button-group>
      </div>
      <div class="layout-side">
        <div class="layout-side">
          <span class="margin-right-5-px">材料名称</span>
          <a-input class="formInput margin-right-5-px" @change="materialN" v-model="selectMaterialM"></a-input>
        </div>
        <a-button-group>
          <a-button icon="search" @click="selectMaterials">查询</a-button>
          <a-button icon="reload" @click="removeSelect">清空</a-button>
        </a-button-group>
      </div>
    </div>
    <a-table
      :locale="{emptyText:'暂无数据'}"
      :rowSelection="rowSelection"
      :rowKey="record => record.key"
      :columns="columns"
      :scroll="{y:contentHeight}"
      :dataSource="totalMaterialData"
      :pagination="paginationMaterial"
    >
      <span slot="tags" slot-scope="tags">
        <a-tag v-for="tag in tags" color="blue" :key="tag">{{tag}}</a-tag>
      </span>
      <span slot="action" slot-scope="text, record">
        <a @click="onViewClick(record.key)">详情</a>
        <template v-if="userType === '2'">
          <a-divider type="vertical"/>
          <a @click="onEditClick(record.key)">修改</a>
          <a-divider type="vertical"/>
          <a-popconfirm title="确定删除该设备？" placement="topRight" @confirm="onDeleteClick(record.key)">
            <a @click="">删除</a>
          </a-popconfirm>
        </template>
      </span>
    </a-table>

    <a-modal
      :title="materialModalTitle"
      width="700px"
      :visible="modalMaterial"
      @cancel="cancelPersonnel"
      :footer="footers">
      <template slot="footer">
        <a-button key="back" icon="reload" @click="handleReset">重置</a-button>
        <a-button v-show="addB" key="add" icon="check" type="primary" :loading="loading" @click="addPersonnel">新增提交</a-button>
        <a-button v-show="!addB" key="update" icon="check" type="primary" :loading="loading" @click="updatePersonnel">修改提交</a-button>
      </template>
      <div class="width-100-per layout-side-na">
        <div class="layout-center-top padding-10-px">
          <div class="layout-side margin-bottom-10-px margin-top-10-px">
            <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>材料名称</div>
            <a-input class="formInput" :disabled="disabled" v-model="materialData.matName"></a-input>
          </div>
          <div class="layout-side margin-bottom-10-px margin-top-10-px">
            <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>编号</div>
            <a-input class="formInput" :disabled="disabled" v-model="materialData.matCode"></a-input>
          </div>
          <div class="layout-side margin-bottom-10-px margin-top-10-px">
            <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>材料类别</div>
            <a-tree-select
              :disabled="disabled"
              class="formInput"
              :value="values"
              :treeData="materialTypesDatas"
              treeDefaultExpandAll
              @select="onSelect"
            />
          </div>


        </div>
        <div class="layout-center-top padding-10-px">
          <div class="layout-side margin-bottom-10-px margin-top-10-px">
            <div class="formSpan">进货日期</div>
            <a-date-picker class="formInput" :value="showTime" :disabled="disabled" @change="onChangeData" />
            <!--            <a-date-picker class="formInput" :value="showData" :disabled="disabled" @change="onChangeData" />-->
          </div>
          <div class="layout-side margin-bottom-10-px margin-top-10-px">
            <div class="formSpan">数量</div>
            <a-input class="formInput" :disabled="disabled" v-model="materialData.matNum"></a-input>
          </div>
          <div class="layout-side margin-bottom-10-px margin-top-10-px">
            <div class="formSpan">备注</div>
            <a-input class="formInput" :disabled="disabled" v-model="materialData.matRemork"></a-input>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
  import {Table, Tag, Divider, Icon, Button, Input, Modal,Popconfirm,Avatar,Select,Upload,DatePicker,TreeSelect} from 'ant-design-vue'
  import {pic2Base64} from '../../lib/utils'
  import moment from 'moment'
  import {indexConfig} from "./IndexConfig";
  import {pagination} from "../../lib/utils";

  export default {
    name: "Material",
    components: {
      ATreeSelect:TreeSelect,
      ADatePicker:DatePicker,
      ATable: Table,
      AModal:Modal,
      ATag: Tag,
      ADivider: Divider,
      AIcon: Icon,
      AButton: Button,
      AButtonGroup: Button.Group,
      AInput:Input,
      APopconfirm:Popconfirm,
      AAvatar:Avatar,
      ASelect:Select,
      ASelectOption:Select.Option,
      AUpload:Upload,
    },
    data() {
      return {
        userType:'0',
        selectMaterialM:'',
        updateID:'',
        dataFormat:'YYYY-MM-DD',
        // dataTme:moment(new Data(),this.dataFormat),
        totalMaterialData:[],
        selectDatees:[],
        values:'请选择',
        materialTypesDatas:[],
        addB:false,
        footers:this.slot,
        disabled:false,
        isMessCount:1,
        materialData:{
          matName:'',
          matCode:'',
          matNum:'',
          // matStarTime:moment(new Date(),this.dataFormat),
          matStarTime:moment().format('YYYY-MM-DD'),
          matRemork:'',
          matParengId:''
        },
        rowSelection:null,
        selectRowMaterial:[],
        loading:false,
        modalMaterial: false,
        materialModalTitle:'新增人员',
        columns:indexConfig.columns,
        updateSomeMaterials:false,
        contentHeight:100,
        paginationMaterial:pagination(this.changePage,this.showSizeChange),
      }
    },
    computed:{
      //时间
      showTime(e){
        return moment(this.materialData.matStarTime ==="" ? new Date():this.materialData.matStarTime,this.dateFormat)
      },
      monitorClientHeight(){
        return this.$store.getters.contentHeight;
      }
    },
    watch:{
      monitorClientHeight:function (old,now) {
        now===0?this.contentHeight = old -400:this.contentHeight = old - 400;
      },
      $route(to,from){
        if(to.query.id === undefined || to.query.id === '999'){
          this.showTables();
        }else {
          this.showTablesByP(to.query.id);
        }
      },
    },
    // computed:{
    // },
    mounted() {
      if(this.$store.getters.contentHeight !== 0){
        this.contentHeight = this.$store.getters.contentHeight - 400;
      }
      this.userType = JSON.parse(this.$store.getters.currentUser).type;
      // if(this.$route.query.id )
      if(this.$route.query.id === undefined || this.$route.query.id === '999'){
        this.showTables();
      }else {
        this.showTablesByP(this.$route.query.id);
      }
      // this.showTables();
      this.dataF();
      this.materialData.matStarTime = moment(this.materialData.matStarTime ==="" ? new Date():this.materialData.matStarTime,this.dateFormat)
    },
    methods: {
      //材料类别查询
      showTablesByP(e){
        const that = this;
        that.totalMaterialData = [];
        that.$apollo.query({
          query: require('../../graphql/material/query/findAllByMatParengId.gql'),
          variables: {id:e},
          fetchPolicy: 'no-cache'
        }).then(data => {
          const findAllMaterial = data.data.findAllByMatParengId;
          for(let i in findAllMaterial){
            that.totalMaterialData.push({
              key: findAllMaterial[i].id,
              matCode: findAllMaterial[i].matCode,
              matName: findAllMaterial[i].matName,
              matNum:findAllMaterial[i].matNum,
              matStarTime:findAllMaterial[i].matStarTime,
            })
          }
          that.selectDatees = that.totalMaterialData;
        }).catch(error => {
          console.log(error);
        })
      },
      //材料名搜索框
      materialN(){
        if(this.selectMaterialM ===""){
          this.totalMaterialData = this.selectDatees;
        }
      },
      //搜索
      selectMaterials(){
        const that = this;
        if(that.selectMaterialM === ""){
          that.$message.error("请填写要搜索的材料名称！");
          return;
        }
        that.totalMaterialData = [];
        for(let i in that.selectDatees){
          if(that.selectMaterialM === that.selectDatees[i].matTypeName){
            that.totalMaterialData.push(that.selectDatees[i])
          }
        }
      },
      //清空
      removeSelect(){
        this.totalMaterialData = this.selectDatees;
        this.selectMaterialM = "";
      },
      //展示数据字典中树的递归函数
      dataTreeDgData(pt, tree) {
        const that = this;
        let newRR = [];
        for (let t of tree) {
          if (pt.id === t.matTypeParentId) {
            let ct = that.dataTreeDgData(t, tree);
            if (ct.length !== 0) {
              newRR.push({
                title: t.matTypeName,
                children: ct,
                key: t.id,
                value: t.id,
                type: 'fatherNode',
              });
            } else {
              newRR.push({
                title: t.matTypeName,
                key: t.id,
                value: t.id,
                type: 'childNode',
              });
            }
          }
        }
        return newRR;
      },
      //材料类型
      dataF(){
        const that = this;
        that.$apollo.query({
          query:require('../../graphql/material/query/findAllMaterialType.gql'),
          variables:{},
          fetchPolicy:'no-cache'
        }).then(data=>{
          const equipmentTree = data.data.findAllMaterialType;
          const newTree = [];
          for (let r of equipmentTree) {
            if (r.matTypeParentId === '999') {
              let ct = that.dataTreeDgData(r, equipmentTree);
              if (ct.length !== 0) {
                newTree.push({
                  title: r.matTypeName,
                  key: r.id,
                  value: r.id,
                  children: that.dataTreeDgData(r, equipmentTree),
                  type: 'fatherNode',
                })
              } else {
                newTree.push({
                  title: r.matTypeName,
                  key: r.id,
                  value: r.id,
                  type: 'childNode',
                })
              }
            }
          }
          that.materialTypesDatas = [{
            title: '材料总览',
            key: '999',
            value:'999',
            children: newTree
          }];
        }).catch(error=>{
          console.log(error)
        })
      },
      //初始表格加载
      showTables(){
        const that =this;
        that.totalMaterialData = [];
        that.$apollo.query({
          query: require('../../graphql/material/query/findAllMaterial.gql'),
          variables: {},
          fetchPolicy: 'no-cache'
        }).then(data => {
          const findAllMaterial = data.data.findAllMaterial;
          for(let i in findAllMaterial){
            that.totalMaterialData.push({
              key: findAllMaterial[i].id,
              matCode: findAllMaterial[i].matCode,
              matName: findAllMaterial[i].matName,
              matNum:findAllMaterial[i].matNum,
              matStarTime:findAllMaterial[i].matStarTime,
            })
          }
          that.selectDatees = that.totalMaterialData;
        }).catch(error => {
          console.log(error);
        })
      },
      //材料上级
      onSelect(value,node,extra){
        this.values=node.title;
        this.materialData.matParengId = value;
      },
      //日期
      onChangeData(date, dateString){
        this.materialData.matStarTime = dateString
      },
      //选择每页多少条后回调
      showSizeChange(current,pageSize){
        this.changePage(current,pageSize)
      },
      //点击页码回调
      changePage(current,pageSize){
        const that = this;
        that.paginationMaterial.defaultPageSize = pageSize;
        that.paginationMaterial.current = current;
      },
      //新增
      addMaterial(){
        this.addB = true;
        this.materialModalTitle = '人员新增';
        this.modalMaterial = true;
      },
      //批量删除按钮
      deleteSomeMaterial(){
        this.updateSomeMaterials = true;
        this.rowSelection = {
          selectRowMaterial:this.selectRowMaterial,
          onChange:this.onSelectChange
        }
      },
      //人员表选择
      onSelectChange(selectedRowKeys){
        this.selectRowMaterial = selectedRowKeys;
      },
      deleteSomeMaterialCancle(){
        this.updateSomeMaterials = false;
        this.selectRowMaterial.length = 0;
        this.rowSelection = null;
      },
      deleteSomeMaterialOK(){
        for(let i in this.selectRowMaterial){
          if(this.selectRowMaterial[i]!== ""){
            this.deleteMaterials(this.selectRowMaterial[i]);
          }
        }
      },
      //人员弹框右上角X按钮
      cancelPersonnel(e) {
        this.modalMaterial = false;
        setTimeout(()=>{
          this.handleReset();
        },100)
      },
      //材料新增确认
      addPersonnel(e) {
        const that = this;
        if(that.materialData.matName === ''){
          that.$message.error('未填写材料名！');
          return;
        }
        if(that.materialData.matParengId === ''){
          that.$message.error('未选择材料类型！');
          return;
        }
        if(that.materialData.matCode === ''){
          that.$message.error('未填写材料编号！');
          return;
        }
        that.loading = true;
        that.$apollo.mutate({
          mutation:require('../../graphql/material/mutation/saveMaterial.gql'),
          variables:{entity:that.materialData},
        }).then((data)=>{
          that.$message.success("新增成功！");
          that.showTables();
          that.handleReset();
          setTimeout(() => {
            this.modalMaterial = false;
            this.loading = false;
          }, 200);
        }).catch(error=>{
          console.log(error);
        })
      },
      //材料修改确认
      updatePersonnel(e) {
        const that = this;
        if(that.materialData.matName === ''){
          that.$message.error('未填写材料名！');
          return;
        }
        if(that.materialData.matParengId === ''){
          that.$message.error('未选择材料类型！');
          return;
        }
        if(that.materialData.matCode === ''){
          that.$message.error('未填写材料编号！');
          return;
        }
        that.loading = true;
        const updaeData=[];
        updaeData.push({
          id:that.updateID,
          matName:that.materialData.matName,
          matCode:that.materialData.matCode,
          matNum:that.materialData.matNum,
          matStarTime:that.materialData.matStarTime,
          matRemork:that.materialData.matRemork,
          matParengId:that.materialData.matParengId,
        })
        that.$apollo.mutate({
          mutation:require('../../graphql/material/mutation/saveMaterial.gql'),
          variables:{entity:updaeData[0]},
        }).then((data)=>{
          that.$message.success("修改成功！");
          that.showTables();
          that.handleReset();
          setTimeout(() => {
            this.modalMaterial = false;
            this.loading = false;
          }, 200);
        }).catch(error=>{
          console.log(error);
        })
      },
      //人员弹框重置按钮
      handleReset() {
        this.disabled = false;
        setTimeout(()=>{
          this.footers = this.slot;
        },200)
        this.materialData={
          matName:'',
          matCode:'',
          matNum:'',
          matStarTime: moment(new Date(),this.dataFormat),
          matRemork:'',
          matParengId:'请选择',
        }
        this.values='请选择'
      },
      onViewClick(id) {
        const that = this;
        that.footers = null;
        that.disabled = true;
        that.materialModalTitle = '人员详情';
        // that.updateID = id;
        that.$apollo.query({
          query:require('../../graphql/material/query/findMaterialById.gql'),
          variables:{id:id},
          fetchPolicy:'no-cache'
        }).then((data)=>{
          const findMaterialById = data.data.findMaterialById;
          this.materialData={
            matName:findMaterialById.matName,
            matCode:findMaterialById.matCode,
            matNum:findMaterialById.matNum,
            matStarTime:findMaterialById.matStarTime,
            matRemork:findMaterialById.matRemork,
            matParengId:findMaterialById.matParengId,
          }
          that.values = findMaterialById.matParengId;
          that.modalMaterial = true;
        }).catch((error)=>{
          console.log(error)
        })
        // this.$emit('onView', id)
      },
      onEditClick(id) {
        const that = this;
        console.log(id)
        that.addB = false;
        that.materialModalTitle = '人员编辑';
        that.$apollo.query({
          query:require('../../graphql/material/query/findMaterialById.gql'),
          variables:{id:id},
          fetchPolicy:'no-cache'
        }).then((data)=>{
          const findMaterialById = data.data.findMaterialById;
          that.materialData={
            matName:findMaterialById.matName,
            matCode:findMaterialById.matCode,
            matNum:findMaterialById.matNum,
            matStarTime:findMaterialById.matStarTime,
            matRemork:findMaterialById.matRemork,
            matParengId:findMaterialById.matParengId,
          }
          that.updateID = findMaterialById.id;
          that.values = findMaterialById.matParengId;
          that.modalMaterial = true;
        }).catch((error)=>{
          console.log(error)
        })
      },
      onDeleteClick(id) {
        this.deleteMaterials(id)
      },
      deleteMaterials(e){
        const that = this;
        that.$apollo.mutate({
          mutation:require('../../graphql/material/mutation/deleteMaterialById.gql'),
          variables:{id:e}
        }).then((data)=>{
          that.showTables();
          that.$message.success("删除成功！");
        }).catch((error)=>{
          that.$message.error("删除失败！");
          console.log(error)
        })
      },
    }
  }
</script>

<style scoped>

</style>

